<?php
// +----------------------------------------------------------------------
// | TYCMS [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.rainfer.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: aliang <461321026@qq.com>
// +----------------------------------------------------------------------
namespace app\home\controller;

use think\Db;

class Center extends Base
{
    public $paystatus = [-1=>"取消",0=>'未知',1=>'待支付',2=>'已支付'];
    public $orderstatus = [-1=>"取消",0=>'未知',1=>'待确认',2=>'待发货',3=>'已发货',4=>'已收货',5=>'已评论',9=>'成交'];
    
	protected function _initialize()
    {
		parent::_initialize();
		$this->check_login();
		$this->assign($this->user);
		
		
		$menu_list  = get_menu_datas(Db::name("model")->where('model_name','member_menu')->value('model_id'));
        $jmenu_list = [];
        foreach($menu_list as $k=>$v){
            if($v['parentid'] > 0){
               $v['url']     = url("home/center/{$v['menu_enname']}");
               $jmenu_list[] = $v;
            }
        }
        $this->assign('user_menu',$jmenu_list);
        
        
         
         
	}
	
 
	public function test(){
	    
	    $info = cache('wxpub_cache');
	    dump($info);exit;
	}
	
	public function _empty(){
	    $maps = [];
	    $action_name        = strtolower(ACTION_NAME);
	    $is_list = $is_show = false;
	    if(strpos($action_name,'_show') !==false){//详细页展示
	       $action_name = str_replace('_show', '', $action_name); 
	       $is_show     = true;
	    }
	    $maps['menu_enname'] = ['eq',$action_name];
	    $maps['menu_open']   = 1; 
	    $info = Db::name("menu")->where($maps)->find();
	    if(empty($info))
	       $this->error('不存在该页面！');
	    $is_list = $info['menu_type'] == 3;
	    $this->assign('menu_name',$info['menu_name']); 
	    if($is_list){//列表类型部分
	        if($is_show){
	          $id      = input('id/d',0);
	          if($id == 0)
	             $this->error('该内容被删除或不存在！');
	          $res = Db::name('news')->where('n_id',$id)->where('news_columnid',$info['id'])->find();
	          if(empty($res))
	              $this->error('该内容被删除或不存在！');
	          $this->assign('ginfo',$res);
	          $this->assign('content',$res['news_scontent']);
	          return $this->view->fetch('user:menu_detail');
	        }else{ 
	          $where["news_columnid"] = $info['id'];
	          $news_list = Db::name('news')->where($where)
	                     ->field("n_id,news_title as title,news_img as img")->order('listorder asc')->paginate(config('paginate.list_rows'));
	          
	          $show = $news_list->render();
	          $this->assign('pager',$show);
	          $this->assign('act',$action_name.'_show');
	          $this->assign("menus_list",$news_list);
	          return $this->view->fetch('user:menu_list');
	        }
	    }else{ //单页详细页部分
	       $this->assign('ginfo',$info);
	       $this->assign('content',$info['menu_content']); 
	       return $this->view->fetch('user:menu_detail');
	       exit;
	    }
	     
	}
	
	 
	
	public function index()
    {
       
        
		return $this->view->fetch('user:center');
    }
    //编辑用户资料
	public function edit()
    {
		$province = Db::name('Region')->where ( array('pid'=>1) )->select ();
		$city=Db::name('Region')->where ( array('pid'=>$this->user['member_list_province']) )->select ();
		$town=Db::name('Region')->where ( array('pid'=>$this->user['member_list_city']) )->select ();
		$this->assign('province',$province);
		$this->assign('city',$city);
		$this->assign('town',$town);
		
		return $this->view->fetch('user:edit');
    }
    public function runedit()
    {
    	if(request()->isPost()){
			$post=input('post.');
			$qrcode = $this->upload('qrcode');
			if($qrcode["err"]==0){
			    $post['qrcode'] = $qrcode["data"];
			}else{
			    unset($post['qrcode']);
			}
			unset($post['money']);
			$rst=Db::name('member_list')->where(array('member_list_id'=>$this->user['member_list_id']))->update($post);
			if ($rst!==false) {
				$this->user = Db::name('member_list')->find($this->user['member_list_id']);
				session('user',$this->user);
				$this->success(lang('save success'),url("home/Center/edit"));
			} else {
				$this->error(lang('save failed'));
			}
    	}
    }
	//修改密码
	public function password()
    {
		return $this->view->fetch('user:password');
    }
	public function runchangepwd()
    {
    	if (request()->isPost()) {
			$old_password=input('old_password');
    		$password=input('password');
			$repassword=input('repassword');
    		if(empty($old_password)){
    			$this->error(lang('old pwd empty'));
    		}
    		if(empty($password)){
    			$this->error(lang('new pwd empty'));
    		}
			if($password!==$repassword){
    			$this->error(lang('pwd not same'));
    		}
			$member=Db::name('member_list');
    		$user=$member->where(array('member_list_id'=>$this->user['member_list_id']))->find();
			$member_list_salt=$user['member_list_salt'];
    		if(encrypt_password($old_password,$member_list_salt)===$user['member_list_pwd']){
				if(encrypt_password($password,$member_list_salt)==$user['member_list_pwd']){
					$this->error(lang('new pwd the same as old pwd'));
				}else{
					$data['member_list_pwd']=encrypt_password($password,$member_list_salt);
					$data['member_list_id']=$this->user['member_list_id'];
					$rst=$member->update($data);
					if ($rst!==false) {
						$this->success(lang('revise success'),url('home/Center/index'));
					} else {
						$this->error(lang('revise failed'));
					}
				}
    		}else{
    			$this->error(lang('old pwd not correct'));
    		}
    	}
    }
	public function avatar()
    {
        $imgurl=input('imgurl');
        //去'/'
        $imgurl=str_replace('/','',$imgurl);
        $rst=Db::name('member_list')->where(array('member_list_id'=>$this->user['member_list_id']))->update(array('member_list_headpic'=>$imgurl));
        if($rst!==false){
            session('user_avatar',$imgurl);
			$this->user['member_list_headpic']=$imgurl;
			$url='/data/upload/avatar/'.$imgurl;
			//写入数据库
			$data['uptime']=time();
			$data['filesize']=filesize('./'.$url);
			$data['path']=$url;
			Db::name('plug_files')->insert($data);
            $this->success (lang('avatar update success'),url('home/Center/index'));
        }else{
            $this->error (lang('avatar update failed'),url('home/Center/index'));
        }
    }
    
    
    //收件地址管理==========
    public function address(){
        $uid  = $this->user['member_list_id'];
        $address_list = Db::name("member_address")->alias("a")->join(config('database.prefix').'member_list b','a.uid = b.member_list_id')
                        ->field("a.*")
                        ->where(array('uid'=>$uid))->order('a.id asc')->paginate(config('paginate.list_rows'));
        $region_list  = Db::name("region")->column('name','id');  
        $show  = $address_list->render();
        
        $list  = $address_list->toArray();
        foreach($list['data'] as $k=>$v){
            $list['data'][$k]['province'] =  isset($region_list[$v['province']]) ? $region_list[$v['province']]:'';
            $list['data'][$k]['city']     =  intval($v['city']) > 0 ? (isset($region_list[$v['city']]) ? $region_list[$v['city']]:''):' ';
            $list['data'][$k]['district'] =  intval($v['district']) > 0 ? (isset($region_list[$v['district']])?$region_list[$v['district']]:''):' ';
        }
        
        $this->assign('page',$show);
        $this->assign("address_list",$list['data']);
        return $this->view->fetch('user:address'); 
    }
    public function delete_address(){
        $id   = input('id',0,'intval');
        $uid  = $this->user['member_list_id'];
        $res  = Db::name('member_address')->where('uid',$uid)->where('id',$id)->delete();
        if($res !== false){
            $this->success ('保存成功！',url('home/Center/address'));
        }else{
            $this->error ('保存失败，请稍候再试！',url('home/Center/address'));
        }
    }
    public function edit_address(){
        $id   = input('id',0,'intval');
        $uid  = $this->user['member_list_id'];
        $info = array();

        if(request()->isPost()){
           $data = input('post.'); 
           $data['uid'] = $uid;
           if(isset($data['is_default']) && $data['is_default'] == 1)
               Db::name('member_address')->where('uid',$uid)->setField('is_default',0);;

           if(isset($data['id']) && $data['id'] > 0){
              $res  = Db::name('member_address')->where("uid",$uid)->where('id',$data['id'])->update($data);
           }else{
              $res  = Db::name('member_address')->insert($data);
           }
           if($res !== false){
               $this->success ('保存成功！',url('home/Center/address'));
           }else{
               $this->error ('保存失败，请稍候再试！',url('home/Center/address'));;
           }
        }
        
        $province_id = 1;
        $city_id     = $this->user['member_list_province'];
        $district_id = $this->user['member_list_city'];
        if($id > 0){
           $info = Db::name("member_address")->where('id',$id)->where('uid',$uid)->find();
           if(empty($info)){
               $this->error ('该记录不存在！',url('home/Center/address'));
           }else{
               $region_list  = Db::name("region")->column('name','id');
               $city_id      = $info['province'];
               $district_id  = $info['city'];
               $info['province_str'] =  $info['province'] > 0 ? (isset($region_list[$info['province']])?$region_list[$info['province']]:''):' ';
               $info['city_str']     =  $info['city'] > 0 ? (isset($region_list[$info['city']]) ? $region_list[$info['city']]:''):' ';
               $info['district_str'] =  $info['district'] > 0 ? (isset($region_list[$info['district']])?$region_list[$info['district']]:''):' ';
           }
        }else{
            $info = array(
                'province' => $this->user['member_list_province'],
                'city'     => $this->user['member_list_city'],
                'district' => 0,
                'is_default'=>0,
            );
            
        }
        
        $province = Db::name('Region')->where ( array('pid'=>1) )->select ();
        $city=Db::name('Region')->where ( array('pid'=>$city_id) )->select ();
        $town=Db::name('Region')->where ( array('pid'=>$district_id) )->select ();
        
        $this->assign('info',$info);
        $this->assign('province',$province);
        $this->assign('city',$city);
        $this->assign('town',$town);
        return $this->view->fetch('user:edit_address');
    }
    
    //我的消息==========
    public function notice(){
        $uid         = $this->user['member_list_id'];
        $notice_list = Db::name("member_notice")->alias("a")->join(config('database.prefix').'member_list b','a.uid = b.member_list_id')
        ->field("a.id,a.title,a.create_time,a.is_read")
        ->where(array('uid'=>$uid))->order('a.id desc')->paginate(config('paginate.list_rows'));
        $show  = $notice_list->render();
    
        $list  = $notice_list->toArray();
        foreach($list['data'] as $k=>$v){
            $list['data'][$k]['create_time'] = date('Y:m:d H:i:s',$v['create_time']);
        }
        $this->assign('page',$show);
        $this->assign("notice_list",$list['data']);
        return $this->view->fetch('user:notice');
    }
    public function notice_info(){
        $uid  = $this->user['member_list_id'];
        $id   = input('id',0,'intval');
        $info = Db::name("member_notice")->where('uid',$uid)->where('id',$id)->find();
        if(empty($info))
          $this->error ('该消息不存在！',url('home/Center/notice'));
        Db::name("member_notice")->where('uid',$uid)->where('id',$id)->setfield("is_read",1);
        $this->assign("info",$info);
        return $this->view->fetch('user:notice_info');
    }   
    public function notice_delete(){
        $uid  = $this->user['member_list_id'];
        $id   = input('id',0,'intval');
        $res  = Db::name("member_notice")->where('uid',$uid)->where('id',$id)->delete();
        if($res !== false){
           $this->success ('操作成功！',url('home/Center/notice'));
        }else{
           $this->error ('操作失败，请稍候再试！',url('home/Center/notice'));;
        }
    }
    
    //====================================
 
    
    public function bang()
    {
    	$oauth_user_model=Db::name("OauthUser");
    	$oauths=$oauth_user_model->where(array("uid"=>$this->user['member_list_id']))->select();
    	$new_oauths=array();
    	foreach ($oauths as $oa){
    		$new_oauths[strtolower($oa['oauth_from'])]=$oa;
    	}
    	$this->assign("oauths",$new_oauths);
		return $this->view->fetch('user:bang');
    }
    public function fav()
    {
		$favorites_model=Db::name("favorites");
        $favorites=$favorites_model->alias("a")->join(config('database.prefix').'news b','a.t_id =b.n_id')->where(array('uid'=>$this->user['member_list_id']))->order('a.id asc')->paginate(config('paginate.list_rows'));
		$show=$favorites->render();
		$this->assign('page',$show);
		$this->assign("favorites",$favorites);
		return $this->view->fetch('user:favorite');
	}
    public function delete_favorite()
    {
        $id=input("id",0,"intval");
        $p=input("p",1,"intval");
        $favorites_model=Db::name("favorites");
        $result=$favorites_model->where(array('id'=>$id,'uid'=>$this->user['member_list_id']))->delete();
        if($result){
            $this->success(lang('cancel collection success'),url('home/Center/fav',array('p'=>$p)));
        }else {
            $this->error(lang('cancel collection failed'));
        }
    }
    
    public function orderlist(){        
        $where["o.uid"] = session("hid");
        $goods = Db::name('goods_order')->alias("o")
            ->join("__GOODS__ g","o.gid = g.id","LEFT")
            ->where($where)
            ->field("o.*,g.goods_title")->order('o.id desc')->paginate(config('paginate.list_rows'));
        $show=$goods->render();
        $this->assign('page',$show);
        $this->assign("orderlist",$goods);
        $this->assign('paystatus',$this->paystatus);
        $this->assign('orderstatus',$this->orderstatus);
        return $this->view->fetch('user:orderlist');
    }
    
    public function vieworder(){
        
        //dump(cache('test_ali_pay');
        $id=input("id",0,"intval");
        $is_chongzhi = false;
        if($id<=0){
            $this->error(lang('operation not valid'));
        }
        $order = Db::name('goods_order')->where(["id"=>$id])->find();
        if(empty($order)){
            $this->error("抱歉，你访问的订单不存在！");
        }
         
        
        if(empty($order["address_cache"]) && $order['order_type'] == 2){
            $this->error("抱歉，收件人信息丢失！");
        }
        
        $order["address_cache"] = unserialize($order["address_cache"]) ; 
        
        $where["g.id"] = $order["gid"];
        $good = Db::name('goods')->alias("g")
            ->join("__GOODS_CATE__ gc","gc.gid = g.id","LEFT")
            ->join("__CATEGORY__ c","c.id = gc.cid","LEFT")
            ->where($where)
            ->field("g.*,c.cate_name")->find();
        $order["goods"][] = $good;
        $order['pay_type_name'] = '其他';
        switch ($order['pay_type']){
            case 'alipay':
                $order['pay_type_name'] = '支付宝支付';
            break;
            case 'wxpayqrcode':
                $order['pay_type_name'] = '微信扫码支付';
            break;
        }
        
        
        $this->assign('order',$order);
        
        $pament_list = config('payment');
        $paylist     = [];
        foreach($pament_list as $k=>$v){
            if(isset($v['display']) && $v['display'] == 1){
                $v['code'] = $k;
                $paylist[] = $v;
            }
        }
        
        $this->assign("paylist",$paylist);
        return $this->view->fetch('user:vieworder');
    }
    
    /*推广网址生成*/
    public function tuiguang(){
        $tuiguang_yuju = config('options.tuiguang_yuju');
        $yuju = explode("\n",$tuiguang_yuju);
        if(empty($this->user['code'])){
           $code =  get_member_code();
           Db::name('member_list')->where("member_list_id",$this->user['member_list_id'])->setField('code',$code);
        }else{
           $code = $this->user['code'];
        }
        $yuju_list = [];
        $url       = config('options.site_host').url('home/tuiguang/index',['code'=>$code]);

        foreach($yuju as $k=>$v){
            $yuju_list[] = [
                'key'=>$k+1,
                'txt'=>str_replace('#url#', $url, $v)
            ];
        }
        $this->assign('code',$code);
        $this->assign("yuju_list",$yuju_list);
        return $this->view->fetch('user:tuiguang');
        
    }
    
    
    /*修改订单操作*/
    public function updateOrder(){
        $res = ['code'=>0,'msg'=>'提交方式错误！'];
        if(request()->isPost()){
           $id    = input('id/d',0,'intval');
           $field = input('field/s',''); 
           $val   = input('val/s','');
           if(empty($field) || empty($val) || empty($id))
              return $res;
           $where  = " id = {$id} and uid =  ".session('hid');
           $result = Db::name("goods_order")->where($where)->setField('pay_type',$val); 
           if($result !==false)
              $res = ['code'=>1,'msg'=>'修改成功！'];
        }
        return $res;
    }
    
    
    
    /*充值余额*/
    public function chongzhi(){
  
        $user = Db::name("member_list")->find(session('hid'));
        $pament_list = config('payment');
        $paylist     = [];
        foreach($pament_list as $k=>$v){
            if(isset($v['display']) && $v['display'] == 1){
                $v['code'] = $k;
                $paylist[] = $v;
            }
        }
 
        $user_money = isset($user['money']) ? (empty($user['money']) ? 0:$user['money']):0;
        $this->assign("user_money",$user_money);
        $this->assign("paylist",$paylist);
        
        return $this->view->fetch('user:chongzhi');
        
    }
    
    
    public function runchongzhi(){
        $data = input('post.');
         
        if($data['fee'] > 0 && !empty($data['pay_type']) ){
          $order = [
                'subject'   => "用户充值({$data['fee']}元)",
                'fee'       => $data['fee'],
                'pay_type'  => $data['pay_type'],
                'order_type'=> 1, //充值类型  order_type = 1
          ];
          $res = write_goods_order($order);
          if($res['code'] == 1){
             $payment_id = $res['data']['payment_id']; 
             $gourl = url('home/payment/payorder',['id'=>$payment_id]);
             $this->redirect($gourl);
          }else{
             $this->error($res['msg']);
          }
        }else{
           $this->error('提交参数存在问题！'); 
        }
        dump($data);exit;
    }
    
    public function myuser(){
        $rst = Db::name('member_list')->where(array('member_list_id'=>$this->user['member_list_id']))->find();
        $pagesize = config('paginate.list_rows');
        $currpage = intval(input("p"));
        $currpage = $currpage <1 ? 1:$currpage;
        if(!empty($rst['code'])){
            $userlist = Db::name('member_list')->where(['procode'=>$rst['code']])->paginate(config('paginate.list_rows'));
            $show = $userlist->render();
        }else{
            $show = "";
            $userlist = [];
        }
        $this->assign('pagesize',$pagesize);
        $this->assign('currpage',$currpage);
        $this->assign('page',$show);
        $this->assign("userlist",$userlist);
        return $this->view->fetch('user:userlist');
    }
    
    public function jiameng(){
        $curr = Db::name('member_group')->where(array('member_group_open'=>1,"member_group_id"=>$this->user["member_list_groupid"]))->find();
        $where=['member_group_open'=>1];
        if($curr){
            $where["member_group_order"] = [">",$curr["member_group_order"]];
        }
        $group = Db::name('member_group')->where($where)->order("member_group_order asc")->select();
        $this->assign('group',$group);
        return $this->view->fetch('user:jiameng');
    }
    
    public function runjiameng(){
        $param = input('post.');
        if(empty($param["member_group_id"])){
            $this->error('提交参数存在问题！');
        }
        $pay_account  = $param["pay_account"];
        $pay_type     = empty($param["pay_type"]) ? "alipay" :$param["pay_type"];
        $member_group = Db::name("member_group")->where(["member_group_id"=>intval($param["member_group_id"])])->find();
        if(empty($member_group)){
            $this->error('会员等级数据错误！');
        }
        
        $data = [
            "subject"  => "加盟升级会员[".$member_group["member_group_name"]."]",
            "pay_type" => $pay_type,
            "sn"       => date("Y").date("m").date('d').date("h").date("i").date("s").random(4,'number'),
            "gid"      => $param["member_group_id"],
            "uid"      => session('hid'),
            "number"   => 1,
            "fee"      =>   $member_group["member_group_money"],
            "total_fee"  => $member_group["member_group_money"],
            "add_time"   => time(),
            "last_time"  => time(),
            "address_id" => 0,
            "order_type" => 3,
            "address_cache"=> ""
        ];
        if(!empty($param["pay_account"])){
            $data["remark"] = $param["pay_account"];
        }
        $res = Db::name('goods_order')->insertGetid($data);
        if($res){
            $this->redirect(url("home/payment/payorder",['id'=>$res])); //创建订单成功，跳转到付款页面
        }else{
            $this->error("抱歉，订单创建失败！");
        }  
        
    }
    
    public function upload($dir){
        $file = request()->file($dir);
        if($file){
            $path =  'data' . DS . 'upload' . DS . $dir;
            $info = $file->validate(['size'=>500000,'ext'=>'jpg,png,gif'])->move(ROOT_PATH .$path);
            if($info){
                return ["err"=>0,"data"=>str_replace("\\",'/',$path."/".$info->getSaveName())];
            }else{
                return ["err"=>1,"msg"=>$file->getError()];
            }
        }else{
            return ["err"=>1,"msg"=>"没有上传文件"];
        }
    }
    
    
    //退出操作
    public function loginout()
    {
        $proCode      =  cookie('procode') ? cookie('procode'):'';
        session(null);
        cookie(null);
        
        if(!empty($proCode))
        cookie('proCode',$proCode,3600*24*7);
        
        $this->redirect(url('home/user/login'));
    }
    
}
